package com.mall.controller;

import com.mall.common.resp.ResponseResult;
import com.mall.common.utils.Security;
import com.mall.controller.vo.CartVO;
import com.mall.entity.Cart;
import com.mall.entity.Goods;
import com.mall.service.CartService;
import com.mall.service.GoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author xyl
 * @date 2021-03-03 17:27
 */
@Api(tags = "购物车接口")
@RestController
@RequestMapping("cart")
public class CartController {

    @Autowired
    private CartService cartService;
    @Autowired
    private GoodsService goodsService;

    @ApiOperation("添加")
    @PostMapping("add")
    public ResponseResult add(@RequestBody @Valid Cart cart, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return ResponseResult.error(bindingResult.getFieldError().getDefaultMessage());
        }
        Goods goods = goodsService.getGoodsById(cart.getGoodsId());
        if(ObjectUtils.isEmpty(goods)){
            return ResponseResult.error("未找到此商品");
        }
        cart.setPrice(goods.getPrice());
        //验证购物车内 该商品不能超过10个
        Cart temp = cartService.getByGoodsIdAndUserId(cart.getGoodsId(), Security.getCurrentUserId());
        if(ObjectUtils.isNotEmpty(temp) && temp.getCount() >= 10){
            return ResponseResult.error("购物车内商品数量不得超过10个");
        }
        return ResponseResult.toResponse(cartService.add(cart));
    }

    @ApiOperation("移除")
    @PostMapping("remove")
    public ResponseResult remove(@RequestParam Integer cartId){
        return ResponseResult.toResponse(cartService.remove(cartId));
    }

    @ApiOperation("当前用户购物车列表")
    @GetMapping("list")
    public List<CartVO> list(){
        return cartService.listVO();
    }
}
